<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择委托单位" prop="name">
        <el-select v-model="queryParams.customerId" placeholder="请选择委托单位" style="width: 240px">
          <el-option v-for="i in userListOptions" :key="i.userId" :label="i.nickName" :value="i.userId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="cardAllSty">
      <el-card shadow="always" style="width: 100%;">
        <div class="allCenter">
          <div class="leftDiv">
            <CalendarAll></CalendarAll>
            <div class="peopleSty">
              <div class="peopleListSty">
                <i class="el-icon-date"></i>
                项目成员
              </div>
              <div style="max-height: 25rem;overflow-y: auto;">
                <div class="listSty" v-for="(item, index) in parPeoList" :key="index">
                  <div style="margin-top: 1rem;">{{ item.projectName }}</div>
                  <div class="avaNameSty" v-for="items in item.userList" :key="items.userId">
                    <el-avatar icon="el-icon-user-solid" size="small" style="margin-right: 0.5rem;"
                      :src="getUrl(items.avatar)"></el-avatar>
                    {{ items.nickName }}
                  </div>
                </div>
              </div>

            </div>
            <div></div>
          </div>
          <div>
            <div style="display: flex;" class="headerSty">
              <el-input placeholder="请输入日程关键词" suffix-icon="el-icon-search" v-model="queryParams.keyWord"
                style="width: 12rem;" @change="searchFull">
              </el-input>
              <div>
                <i class="el-icon-arrow-left" @click="prevMonth"></i>
                <span>{{ currentYear }}年{{ currentMonth }}月</span>
                <i class="el-icon-arrow-right" @click="nextMonth"></i>
              </div>
              <!-- @click="handleUpdateTask" -->
              <!-- <el-button type="primary" icon="el-icon-plus">更改日程</el-button> -->
              <div></div>
            </div>
            <fullCalendar :calendarEventsList="calendarEventsList" @handleDetail="handleDetail" ref="fullCalendarDio">
            </fullCalendar>
          </div>
        </div>

      </el-card>
    </div>
    <Detail v-if="detailVisible" ref="Detail" @refreshDetail="refreshDetail" />
    <!-- <editFloorList v-if="editFloorVisible" ref="Detail" @refresh="editFloorVisible = false" /> -->
    <taskDetail v-if="taskDetailVisible" ref="taskDetail"></taskDetail>
    <updateTask v-if="updateTaskVisible" ref="updateTask"></updateTask>
  </div>
</template>

<script>
import { getUserList, getProjectPlanByCustomerId, getProjectUsers, getSchedulesList } from "@/api/plan-produce/task";
import fullCalendar from "./cp/fullCalendar.vue";
import Detail from "./cp/detail.vue";
import taskDetail from '../task/task-detail.vue'
import CalendarAll from "./cp/calendarAll.vue";
import updateTask from './cp/update-task.vue'
export default {
  name: "Building",
  components: {
    //  editFloorList,
    taskDetail,
    Detail,
    updateTask,
    CalendarAll,
    fullCalendar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 详情页面
      detailVisible: false,
      // 编辑楼层
      editFloorVisible: false,
      taskDetailVisible: false,
      updateTaskVisible: false,
      // 委托单位列表
      userListOptions: [],
      input2: '',
      calendarEventsList: [],

      value: new Date(),
      // 查询参数
      queryParams: {
        customerId: null,
        keyWord: null
      },
      currentMonth: '',
      currentYear: '',
      currentDate: new Date(),

      // 表单参数
      form: {},

      //参与人员列表 
      parPeoList: [],

      // 初始化日期变量  
      firstDay: null,
      lastDay: null

    };
  },
  created() {
    this.getList();


  },

  methods: {
    getList() {
      this.loading = true;
      // 获取用户列表
      getUserList('02').then((response) => {
        this.userListOptions = response.data;
        // 默认第一个
        this.queryParams.customerId = response.data[0].userId
        // this.getProjectUsersList(response.data[0].userId)
        this.loading = false;
        this.$nextTick(() => {
          this.generateCalendar()
        })
      });

    },
    // 跳转详情
    handleDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    // 更改日程
    handleUpdateTask() {
      this.updateTaskVisible = true;
      this.$nextTick(() => {
        this.$refs.updateTask.init();
      });
    },
    getProjectUsersList(id) {
      getProjectUsers(id).then(res => {
        this.parPeoList = res.data
      })
      this.calendarEventsList = []
      // 查询本月日程 
      getSchedulesList(id, { beginTime: this.firstDay, endTime: this.lastDay, keyWord: this.queryParams.keyWord }).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          let list = res.data[i].projectList
          for (let j = 0; j < list.length; j++) {
            this.calendarEventsList.push({
              id: list[j].subPlanId,
              title: list[j].projectName,
              start: new Date(res.data[i].time).getTime(),
              editable: false,
              allDay: false,
              end: new Date(res.data[i].time).getTime(),
              time: res.data[i].time
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getUrl(url) {
      return process.env.VUE_APP_WEBSC_API + url
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceOrgId: null,
        customerId: null,
        name: null,
        address: null,
        pointPositionDesc: null,
        abovegroundNumber: null,
        undergroundNumber: null,
        longitude: null,
        latitude: null,
        invalid: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getProjectUsersList(this.queryParams.customerId)
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      // this.handleQuery();
      this.getList()
    },
    // 跳转详情
    handleDetail(id, time) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id, time);
      });
    },
    refreshDetail(list) {
      this.detailVisible = false;
      setTimeout(() => {
        this.taskDetailVisible = true;
        this.$nextTick(() => {
          this.$refs.taskDetail.init(list);
        });
      }, 0);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBuilding(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBuilding(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    calculateDates() {

      const now = new Date();
      // 获取当前月的第一天
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
      // 获取当前月的最后一天
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      this.firstDay = this.formatDate(firstDay)
      this.lastDay = this.formatDate(lastDay);
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (1 + date.getMonth()).toString().padStart(2, '0'); // 月份从0开始，所以加1  
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    generateCalendar() {
      // 更新当前月份和年份  
      this.currentMonth = (this.currentDate.getMonth() + 1).toString().padStart(2, '0');
      this.currentYear = this.currentDate.getFullYear();
      this.firstDay = this.getMonthStartAndEnd(this.currentDate).start
      this.lastDay = this.getMonthStartAndEnd(this.currentDate).end
      this.$nextTick(() => {
        this.getProjectUsersList(this.queryParams.customerId)
      })
    },
    searchFull() {
      this.getProjectUsersList(this.queryParams.customerId)
    },
    // 计算月开始结束时间
    getMonthStartAndEnd(dateStr) {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = date.getMonth(); // 注意：JavaScript中月份是从0开始计数的，所以5月是4  

      // 月开始时间  
      const startOfMonth = new Date(year, month, 1, 0, 0, 0, 0);

      // 查找月结束时间（考虑到不同月份天数不同）  
      const nextMonth = month + 1;
      const nextMonthFirstDay = new Date(year, nextMonth, 1, 0, 0, 0, 0);
      const endOfMonth = new Date(nextMonthFirstDay - 1); // 前一天的日期即为当前月的最后一天  
      // 格式化日期为 "YYYY-MM-DD"  
      const formatDate = (date) => {
        const pad = (num) => num < 10 ? '0' + num : num;
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
      };
      return {
        start: formatDate(startOfMonth),
        end: formatDate(endOfMonth)
      };
    },
    prevMonth() {
      this.currentDate.setMonth(this.currentDate.getMonth() - 1);
      this.generateCalendar();
      this.$refs.fullCalendarDio.listPrev()

    },
    nextMonth() {
      this.currentDate.setMonth(this.currentDate.getMonth() + 1);
      this.generateCalendar();
      this.$refs.fullCalendarDio.listNext()
    },
  },
};
</script>
<style lang="scss">
.cardAllSty {
  width: 100%;

  .allCenter {
    display: flex;

    .leftDiv {}

    .peopleSty {}

    .peopleListSty {
      font-size: 14px;
      // font-weight: bold;
      padding-left: 1rem;
      color: #555;
    }

    .listSty {
      font-size: 12px;
      padding-left: 2rem;
      // overflow-y: auto;

    }

    .avaNameSty {
      display: flex;
      align-items: center;
      padding: 0.5rem;
    }

  }

}

.headerSty {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>